/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.gui;

import java.util.*;

import blueprint4j.utils.*;

public class AnimationThread extends LogThread {
	private static Vector animations=new Vector();
	private static double smallest_framegap=100;

	private AnimationThread(){
		super();
	}

	public static void add(Animation animation){
		AnimationDetails details=new AnimationDetails(animation);
		animations.add(details);
		if (details.framegap<smallest_framegap){
			smallest_framegap=details.framegap;
		}
	}

	public static void remove(Animation animation){
		for (int t=0;t<animations.size();t++){
			AnimationDetails details=(AnimationDetails)animations.get(t);
			if (details.animation==animation){
				// Remove this one
				animations.remove(details);
				if (details.framegap==smallest_framegap){
					// Find new framegap
					smallest_framegap=100;
					for (int p=0;p<animations.size();p++){
						details=(AnimationDetails)animations.get(p);
						if (details.framegap<smallest_framegap){
							smallest_framegap=details.framegap;
						}
					}
				}
			}
		}
	}

	public void run(){
		double time=System.currentTimeMillis();
		Log.trace.out("Animations","The animation thread has been started");
		while (!mustShutdown()){
			// Check animations
			for (int t=0;t<animations.size();t++){
				AnimationDetails details=(AnimationDetails)animations.get(t);
				long timer=System.currentTimeMillis();
				details.animate(timer);
			}
			try {
				// Sleep
				Thread.sleep((long)(smallest_framegap*.8d));
			} catch (InterruptedException ie){
				Log.debug.out(ie);
			}
		}
		Log.trace.out("Animations","The animation thread has been stopped");
	}

	static {
		// Create main instance
		new AnimationThread().start();
	}
}

